﻿namespace LiSAClient.WpfClient.Utils
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;

    /// <summary>
    /// This class forces the assemblies to be loaded during startup.
    /// </summary>
    public class AssemblyLoader
    {
        public static void AssemblyInitializer(object sender, AssemblyLoadEventArgs args)
        {
            // force static constructors in types specified by InitializeOnLoad
            foreach (
                InitializeOnLoadAttribute attr in
                    args.LoadedAssembly.GetCustomAttributes(typeof(InitializeOnLoadAttribute), false))
            {
                System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(attr.Type.TypeHandle);
            }
        }

        public static void Load()
        {
            var assemblies = new List<Assembly>();
            var files = Directory.GetFiles(AssemblyDirectory, "*.dll", SearchOption.AllDirectories);
            foreach (var dll in files)
            {
                assemblies.Add(Assembly.LoadFrom(dll));
            }
        }

        private static string AssemblyDirectory
        {
            get
            {
                var path = GetAssemblyPath(Assembly.GetExecutingAssembly());
                return Path.GetDirectoryName(path);
            }
        }

        private static string GetAssemblyPath(Assembly ass)
        {
            var codeBase = ass.CodeBase;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);

            return path;
        }

    }
}
